import axios from '@/plugins/axios'
import { IStore } from '@/types/index'
import { AxiosRequestConfig } from 'axios'
import { Commit, createStore } from 'vuex'
const asyncAndCommit = async (
  url: string,
  mutationName: string,
  commit: Commit,
  config: AxiosRequestConfig = { method: 'get' }
) => {
  const { data } = await axios(url, config)
  commit(mutationName, data)
  return data
}
export default createStore<IStore>({
  state: {
    token: localStorage.getItem('token') || '',
    loading: false,
    user: { isLogin: false },
    columnList: [],
    postsList: [],
    error: {
      status: false
    }
  },
  getters: {
    getColumnById: (state) => (id: string) => {
      return state.columnList.find((o) => o._id === id)
    },
    getPostsListByCId: (state) => (id: string) => {
      return state.postsList.filter((o) => o.column === id)
    },
    getPostsById: (state) => (id: string) => {
      return state.postsList.find((posts) => posts._id === id)
    }
  },
  mutations: {
    login(state, data) {
      state.token = data.token
      localStorage.setItem('token', data.token)
    },
    logout(state) {
      state.token = ''
      state.user = { isLogin: false }
      localStorage.removeItem('token')
    },
    setUserInfo(state, data) {
      state.user = { isLogin: true, ...data }
    },
    getColumns(state, rawData) {
      if (rawData.currentPage === 1) {
        state.columnList = rawData.list
      } else {
        state.columnList = [...state.columnList, ...rawData.list]
      }
    },
    getColumn(state, rawData) {
      state.columnList = [rawData]
    },
    getPostsList(state, rawData) {
      if (rawData.currentPage === 1) {
        state.postsList = rawData.list
      } else {
        state.postsList = [...state.postsList, ...rawData.list]
      }
    },
    getPosts(state, rawData) {
      state.postsList = [rawData]
    },
    createPosts(state, rawData) {
      state.postsList.push(rawData)
    },
    updatePosts(state, rawData) {
      state.postsList = state.postsList.map((posts) => {
        if (posts._id === rawData._id) {
          return rawData
        } else {
          return posts
        }
      })
    },
    deletePosts(state, rawData) {
      state.postsList = state.postsList.filter(
        (posts) => posts._id !== rawData._id
      )
    },
    setLoading(state, status) {
      state.loading = status
    },
    setError(state, e) {
      state.error = e
    }
  },
  actions: {
    // 登录
    login({ commit }, payload) {
      return asyncAndCommit('/user/login', 'login', commit, {
        method: 'post',
        data: payload
      })
    },
    // 获取用户信息
    getUserInfo({ commit }) {
      return asyncAndCommit('/user/current', 'setUserInfo', commit)
    },
    // 登录并且获取用户信息
    loginAndGet({ dispatch }, loginData) {
      return dispatch('login', loginData).then(() => {
        return dispatch('getUserInfo')
      })
    },
    // 获取column列表
    getColumns({ commit }, params) {
      return asyncAndCommit('/columns', 'getColumns', commit, {
        method: 'get',
        params
      })
    },
    // 获取colum详情
    getColumn({ commit }, columnId) {
      return asyncAndCommit(`/columns/${columnId}`, 'getColumn', commit)
    },
    // 获取posts列表
    getPostsList({ commit }, { columnId, ...params }) {
      console.log(params)
      return asyncAndCommit(
        `/columns/${columnId}/posts`,
        'getPostsList',
        commit,
        {
          method: 'get',
          params
        }
      )
    },
    // 获取posts
    getPosts({ commit }, postsId) {
      return asyncAndCommit(`/posts/${postsId}`, 'getPosts', commit)
    },
    // 创建posts
    createPosts({ commit }, payload) {
      return asyncAndCommit(`/posts`, 'createPosts', commit, {
        method: 'post',
        data: payload
      })
    },
    // 更新posts
    updatePosts({ commit }, { id, payload }) {
      return asyncAndCommit(`/posts/${id}`, 'updatePosts', commit, {
        method: 'patch',
        data: payload
      })
    },
    // 删除posts
    deletePosts({ commit }, postsId) {
      return asyncAndCommit(`/posts/${postsId}`, 'deletePosts', commit, {
        method: 'delete'
      })
    }
  },
  modules: {}
})
